package my.edu.api;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.EntityBuilder;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;


@Component
public class LogisticsServiceImpl implements LogisticsService {

    static String URL = "http://send.wxbus163.cn/express/getLogistics";
    static  String KEY_SECRET = "fa90fd6232e69251b02f2f11c64cd3cb";
    static  String UNAME = "2843372318@qq.com";

    @Override
    public JSONObject getLogistics(String logisticsNo, String phoneLastFour) {
        HttpPost httpPost = new HttpPost(URL);
        httpPost.setHeader("User-Agent", "PostmanRuntime-ApipostRuntime/1.1.0");
        httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
        httpPost.setHeader("Cache-Control", "no-cache");
        httpPost.setHeader("Accept", "*/*");

        // 使用 MultipartEntityBuilder 构建 multipart/form-data 请求体
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addTextBody("express_no", logisticsNo, ContentType.create("text/plain", StandardCharsets.UTF_8));
        builder.addTextBody("uname", UNAME, ContentType.create("text/plain", StandardCharsets.UTF_8));
        builder.addTextBody("keySecret", KEY_SECRET, ContentType.create("text/plain", StandardCharsets.UTF_8));

        if (phoneLastFour != null) {
            builder.addTextBody("phone", phoneLastFour, ContentType.TEXT_PLAIN);
        }

        HttpEntity entity = builder.build();
        httpPost.setEntity(entity);

        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse response = httpClient.execute(httpPost)) {
                String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
                return JSONUtil.parseObj(responseBody);
        } catch (ParseException e) {
            e.printStackTrace();
            return JSONUtil.parseObj("{\"msg\":\"物流端口获取失败\"}");
        } catch (IOException e) {
            e.printStackTrace();
            return JSONUtil.parseObj("{\"msg\":\"物流端口获取失败\"}");
        }
    }
}
